<!--
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-10 14:03:13
 * @LastEditTime: 2023-05-25 15:05:34
-->
<script lang="ts" setup name="DictionItem">
import type { Ref } from 'vue'
import useUserStore from '@g/store/modules/user'
import { dictApi } from '@/MainApp/apis/dict'

const emits = defineEmits<{
  (e: 'selectItem', val: typeof formKey): void
}>()
const { lenContent, lenName } = useLength()
const { dialog, t } = useConfig()
const { msgSuccess, msgError, msgBoxWarnAsync } = useMessage()

const formKey = {
  // 字典名称
  name: '',
  // 字典类型
  type: 'BUSINESS' as 'BUSINESS' | 'SYSTEM',
  // 备注信息
  remark: '',
  // 字典项能否删除
  itemDeletable: true,

  // 字典是否可见
  visible: true
}
const placeholder = {
  name: '请输入字典名称',
  remark: '请输入备注信息'
}

const itemRules = {
  name: [{ required: true, message: placeholder.name, trigger: 'blur' }],
  type: [{ required: false, message: '', trigger: 'change' }],
  visible: [{ required: false, message: '', trigger: 'change' }],
  itemDeletable: [{ required: false, message: '', trigger: 'change' }]
}
const itemRef = ref()
const itemForm = ref({ ...formKey })
const itemState = reactive({
  visible: false,
  loading: false,
  itemData: [],
  isEditing: false
})
const title = computed(() => (itemState.isEditing ? '修改字典' : '新增字典'))

const refItem: Ref<any> = ref(null)
// 查询
const getDictionary = async () => {
  const { msg, success, data } = await dictApi.getDictionary()
  if (success) {
    itemState.itemData = data || []
    nextTick(() => {
      // 默认选择第一条、并显示第一条下的字典项
      refItem.value?.table?.table?.setCurrentRow(data[0])
    })
  }
  else { msgError(msg) }
}
// getDictionary()
const handSelectItem = (row: typeof formKey) => {
  row && emits('selectItem', row)
}

// 新增
const handAddDictItem = () => {
  itemState.isEditing = false
  itemState.visible = true
  itemRef.value?.resetFields()
}

// 关闭
const handleClose = () => {
  itemRef.value?.resetFields()
  itemState.visible = false
  itemState.isEditing = false
  nextTick(() => {
    itemForm.value = { ...formKey }
  })
}
const userStore = useUserStore()
// 确认
const handConfirm = () => {
  itemRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      itemState.loading = true
      const { msg, success } = itemState.isEditing
        ? await dictApi.updateDictItem({ ...itemForm.value })
        : await dictApi.addDictItem({ ...itemForm.value })
      if (success) {
        msgSuccess(msg)
        getDictionary()
        handleClose()
        // 更新storage中的字典数据
        userStore.getAllDiction()
      }
      else { msgError(msg) }

      itemState.loading = false
    }
  })
}

// 修改
const handEditRow = (row: typeof formKey) => {
  itemState.isEditing = true
  itemForm.value = { ...row }
  itemState.visible = true
}
// 删除
const handDelete = (row: { id: string; name: string; }) => {
  msgBoxWarnAsync('删除确认', `删除后，字典【${row.name}】及其所有的字典项将被一并删除，相关业务数据也有可能出现异常，确定删除吗？`, async () => {
    const { msg, success } = await dictApi.deleteDictItem(row.id)
    if (success)
      getDictionary()
    else
      msgError(msg)
  })
}

const fields = [{
  key: 'name',
  label: '名称',
  show: true
}, {
  key: 'remark',
  label: '描述',
  show: true
}, {
  key: '',
  label: '操作',
  show: true,
  width: useOperateWidth(106, 120),
  showOverflowTooltip: false,
  tableSlot: 'operate',
  fixed: 'right'
}]
</script>

<template>
  <IkPageFull
    ref="refItem"
    :fields="fields"
    tab-id="content"
    highlight-current-row
    :table-data="itemState.itemData"
    :search="getDictionary"
    header-title="字典列表"
    @current-change="handSelectItem"
  >
    <template #headerRight>
      <IkSvgIcon
        v-role="'ADD-DICT'"
        :size="20"
        name="iksvg_xinzeng"
        show-bg
        title="新增"
        pop
        :start-margin="false"
        @click="handAddDictItem"
      />
    </template>
    <template #operate="{ data }">
      <IkBtnContent :num="4">
        <IkSvgIcon
          v-role="'UPDATE-DICT'"
          name="icon-bianji"
          show-bg
          pop
          in-table
          :title="t('action.modify')"
          @click="handEditRow(data.row)"
        />
        <IkSvgIcon
          v-role="'DELETE-DICT'"
          name="icon-shanchu"
          show-bg
          pop
          in-table
          type="danger"
          :title="t('action.delete')"
          @click="handDelete(data.row)"
        />
      </IkBtnContent>
    </template>
  </IkPageFull>
  <!-- 新增、修改 -->
  <el-dialog
    v-model="itemState.visible"
    :title="title"
    draggable
    :width="dialog.sl"
    :close-on-click-modal="false"
    class="dict-item"
    @closed="handleClose"
  >
    <el-form
      ref="itemRef"
      :model="itemForm"
      :rules="itemRules"
      label-width="90px"
      label-position="top"
    >
      <el-form-item label="字典名称" prop="name">
        <el-input
          v-model.trim="itemForm.name"
          :maxlength="lenName"
          show-word-limit
          :placeholder="placeholder.name"
        />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model.trim="itemForm.remark"
          :maxlength="lenContent"
          show-word-limit
          type="textarea"
          :autosize="{ minRows: 4 }"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button
        bg
        text
        @click="handleClose"
      >
        {{ t("action.cancel") }}
      </el-button>
      <el-button type="primary" :loading="itemState.loading" @click="handConfirm">
        {{ t("action.sure") }}
      </el-button>
    </template>
  </el-dialog>
</template>
